package com.glory.wxelectricitypda.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.base.Constant;
import com.glory.wxelectricitypda.bean.AuthorityEntity;
import com.glory.wxelectricitypda.bean.BaseResponseBean;
import com.glory.wxelectricitypda.bean.LoginBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_PasswordEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends FreeUI_BaseActivity {


    @BindView(R.id.tvVersion)
    TextView tvVersion;
    @BindView(R.id.ivBanner)
    ImageView ivBanner;
    @BindView(R.id.etMobile)
    FreeUI_ClearEditText etMobile;
    @BindView(R.id.etPassword)
    FreeUI_PasswordEditText etPassword;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;

    private FreeUI_GeneralFragmentDialog freeUI_generalFragmentDialog;
    private FreeUI_DownloadFragmentDialog dialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    etPassword.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {
        FreeApi_Utils.deleteLog();
        tvVersion.setText(String.valueOf(Constant.VERSION_CODE));
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (dialog == null) {
            requestUpdate();
        }
    }

    private void requestUpdate() {
        NetUtils.requestUpdate(new FreeUI_DialogEntityCallBack<FreeUI_VersionEntity>(
                new TypeToken<FreeUI_VersionEntity>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity versionEntity = response.body();
                if (Integer.parseInt(versionEntity.getVersion()) != Constant.VERSION_CODE) {
                    versionEntity.setApkName(getString(R.string.app_name));
                    versionEntity.setCurrentVersion(String.valueOf(Constant.VERSION_CODE));
                    dialog = new FreeUI_DownloadFragmentDialog();
                    dialog.setData(versionEntity);
                    dialog.show(getSupportFragmentManager(), "dialog_down_new");
                }
            }

            @Override
            public void onError(Response<FreeUI_VersionEntity> response) {
                super.onError(response);
                loadError(response.getException(), "requestUpdate");
            }
        });
    }

    @OnClick({R.id.btnLogin, R.id.ivSetting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                final String userName = etMobile.getText().toString().trim();
                if (userName.length() == 0) {
                    showToast("请输入用户名", false);
                    return;
                }
                if (etPassword.getText().toString().trim().length() == 0) {
                    showToast("请输入密码", false);
                    return;
                }
                JSONObject map = new JSONObject();
                try {
                    map.put("USERNAME", userName);
                    map.put("PASSWORD", etPassword.getText().toString().trim());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                eaplotIn(map,userName);
//                meslotIn(map,userName);
                break;
            case R.id.ivSetting:
                freeUI_generalFragmentDialog = FreeApi_DialogUtils.getScanDialog(this, "请输入管理员密码", new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        if (s.equals("1314")) {
                            Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
                            intent.putExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY, "header");
                            startActivity(intent);
                            freeUI_generalFragmentDialog.dismiss();
                        } else {
                            showToast("密码错误", false);
                        }
                    }
                });
                freeUI_generalFragmentDialog.show(getSupportFragmentManager(), "PASSWORD_VERIFY");
                break;
        }
    }

    private void meslotIn(JSONObject map,String userName) {
        NetUtils.requestLogin(map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LoginBean>>(
                new TypeToken<BaseResponseBean<LoginBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<LoginBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), false)) {
                    showToast("登陆成功", true);
//                    Constant.CURRENT_USER = userName;
                    Constant.IS_CARRIER = response.body().getResponse().getBody().getISCARRIER();
                    requestAuthority();

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LoginBean>> response) {
                super.onError(response);
                loadError(response.getException(), "EUIT.EUITLOGIN");
            }
        });
    }

    private void eaplotIn(JSONObject map,String userName) {
        NetUtils.requestPostUtils("login","Login",map, this,new FreeUI_DialogEntityCallBack<ResponseBean<LoginBean>>(
                new TypeToken<ResponseBean<LoginBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LoginBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showToast("登陆成功", true);
                    Constant.CURRENT_USER = userName;
                    FreeApi_SharePreferencesUtils.setSharePre("URL_FILE", "USE_NAME", userName, getApplicationContext());
                    Constant.IS_CARRIER = response.body().getBody().getISCARRIER();
                    requestAuthority1();
//                            startActivity(new Intent(getApplicationContext(), HomeActivity.class));
//                            LoginActivity.this.finish();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LoginBean>> response) {
                super.onError(response);
                loadError(response.getException(), "Login");
            }
        });
    }

    private void requestAuthority() {
        JSONObject map = new JSONObject();
        try {
            map.put("AUTHORITYCATEGORY", "PDA");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestAuthority(map, new FreeUI_DialogEntityCallBack<BaseResponseBean<AuthorityEntity>>(
                new TypeToken<BaseResponseBean<AuthorityEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<AuthorityEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), false)) {
                    if (response.body().getResponse().getBody().getXALIST().isEmpty()){
                        showToast("当前登录用户无任何权限",false);
                        return;
                    }


                    for (AuthorityEntity.AuthorityInfoEntity authorityInfoEntity : response.body().getResponse().getBody().getXALIST()) {
                        Constant.AUTHORITY_LIST.add(authorityInfoEntity.getLABELZH());
                    }
                    startActivity(new Intent(getApplicationContext(), HomeActivity.class));
                    LoginActivity.this.finish();

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AuthorityEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "EUIT.EUITAUTHORITY");
            }
        });

    }


    private void requestAuthority1() {
        JSONObject map = new JSONObject();
        try {
            map.put("AUTHORITYCATEGORY", "PDA");
            map.put("AUTHORITYTYPE", "");
            map.put("PARENTRRN", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostUtils("authority","Authority",map, this,new FreeUI_DialogEntityCallBack<ResponseBean<AuthorityEntity>>(
                new TypeToken<ResponseBean<AuthorityEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<AuthorityEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
//                    if (response.body().getResponse().getBody().getXALIST().isEmpty()){
//                        showToast("当前登录用户无任何权限",false);
//                        return;
//                    }

                    if (response.body().getBody() != null) {
                        for (AuthorityEntity.AuthorityInfoEntity authorityInfoEntity : response.body().getBody().getXALIST()) {
                            Constant.AUTHORITY_LIST.add(authorityInfoEntity.getLABELZH());
                        }
                    }
                    startActivity(new Intent(getApplicationContext(), HomeActivity.class));
                    LoginActivity.this.finish();

                }
            }

            @Override
            public void onError(Response<ResponseBean<AuthorityEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "Authority");
            }
        });

    }

    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();

    // private ImageView welcomeImg = null;
    private static final int PERMISSION_REQUEST = 1;
// 检查权限

    private void checkPermission() {
        mPermissionList.clear();
        //判断哪些权限未授予
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST);
        }
    }
    /**
     * 响应授权
     * 这里不管用户是否拒绝，都进入首页，不再重复申请权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }


}

